package com.moyun.modelclass.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.opengl.GLException;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.blankj.utilcode.util.ClickUtils;
import com.blankj.utilcode.util.EncryptUtils;
import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallback;
import com.moyun.modelclass.R;
import com.moyun.modelclass.base.BaseModelActivity;
import com.moyun.modelclass.http.OSSHelper;
import com.moyun.modelclass.http.api.CheckFileApi;
import com.moyun.modelclass.http.api.RelateThumbnailApi;
import com.moyun.modelclass.http.api.UpdateImageApi;
import com.moyun.modelclass.http.model.HttpData;
import com.moyun.modelclass.utils.StatusBarUtil;
import com.moyun.modelclass.view.gifshow.widget.stlview.callback.OnReadCallBack;
import com.moyun.modelclass.view.gifshow.widget.stlview.widget.STLView;
import com.moyun.modelclass.view.gifshow.widget.stlview.widget.STLViewBuilder;
import com.moyun.modelclass.view.preview.ThumbnailUtils;

import java.io.File;
import java.nio.IntBuffer;
import java.util.UUID;

import javax.microedition.khronos.opengles.GL10;

/**
 * 作者：Meteor
 * 日期：2022/1/15 17:25
 * tip：编辑模型时模型预览
 */
public class EditModelPreviewActivity extends BaseModelActivity {
    private RelativeLayout rlEditModelPreviewTop;
    private ImageView ivEditModelPreviewBack;
    private STLView stlEditModelPreview;
    private TextView tvEditEditModelPreviewUpload;
    private String mFilePath = "";//本地模型路径
    private File thumbnailFile = null;//生成的预览图
    private String modelUrl = "";//模型地址
    private String modelThumbnail = "";//模型预览图

    private OSSHelper oSSHelper = null;

    public static void start(Activity context, String filePath, int code) {
        Intent starter = new Intent(context, EditModelPreviewActivity.class);
        starter.putExtra("filePath", filePath);
        context.startActivityForResult(starter, code);
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_edit_model_preview;
    }

    @Override
    protected void assignViews() {
        rlEditModelPreviewTop = (RelativeLayout) findViewById(R.id.rl_edit_model_preview_top);
        ivEditModelPreviewBack = (ImageView) findViewById(R.id.iv_edit_model_preview_back);
        stlEditModelPreview = (STLView) findViewById(R.id.stl_edit_model_preview);
        tvEditEditModelPreviewUpload = (TextView) findViewById(R.id.tv_edit_edit_model_preview_upload);

        StatusBarUtil.setPaddingSmart(this, rlEditModelPreviewTop);
    }

    @Override
    protected void registerListeners() {
        ClickUtils.applySingleDebouncing(ivEditModelPreviewBack, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });

        ClickUtils.applySingleDebouncing(tvEditEditModelPreviewUpload, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!mFilePath.isEmpty() && thumbnailFile != null) {
                    upLoadStlFile();
                }
            }
        });
    }

    @SuppressLint("SetTextI18n")
    @Override
    protected void getExtras(Bundle bundle) {
        mFilePath = bundle.getString("filePath", "");
    }

    @Override
    protected boolean isRegisterEventBus() {
        return false;
    }

    @Override
    protected void doAction() {
        loadStlModel();
    }

    //上传模型
    private void upLoadStlFile() {
        File mainStlFile = new File(mFilePath);
        String mainStlEncryptMD5 = EncryptUtils.encryptMD5File2String(mFilePath);
        String mainStlExtension = FileUtils.getFileExtension(mFilePath);
        long mainStlSize = FileUtils.getLength(mainStlFile);
        EasyHttp.post(this)
                .api(new CheckFileApi().setMd5(mainStlEncryptMD5).setExtName(mainStlExtension))
                .request(new HttpCallback<HttpData<CheckFileApi.Bean>>(this) {
                    @Override
                    public void onSucceed(HttpData<CheckFileApi.Bean> md5Result) {
                        if (md5Result == null || md5Result.getData() == null) {
                            return;
                        }

                        if (md5Result.getData().isExist()) {
                            Log.e("showProgressDialog==>", "文件已经存在，不需要上传");
                            modelUrl = md5Result.getData().getUrl();
                            modelThumbnail = md5Result.getData().getThumbnail();
                            Intent intent = new Intent();
                            intent.putExtra(EditModelActivity.KEY_EDIT_MODEL_URL, modelUrl);
                            intent.putExtra(EditModelActivity.KEY_EDIT_MODEL_THUMBNAIL, modelThumbnail);
                            setResult(Activity.RESULT_OK, intent);
                            finish();
                            return;
                        }
                        showProgressDialog();
                        oSSHelper = OSSHelper.getInstance(new OSSHelper.OnOssUpLoadStateListener() {
                            @Override
                            public void onSuccess(PutObjectRequest request, PutObjectResult result, String fileId, String fileUrl) {

                                Log.e("showProgressDialog==>", "文件上传成功");
                                modelUrl = fileUrl;
                                uploadModelThumbnail(fileId);
                            }

                            @Override
                            public void onFailure(PutObjectRequest request, ClientException clientException, ServiceException serviceException) {
                                dismissProgressDialog();
                                ToastUtils.showShort("上传失败");
                                Log.e("showProgressDialog==>", "上传失败");
                            }
                        });
                        oSSHelper.init(EditModelPreviewActivity.this, false, mainStlExtension, mFilePath, mainStlSize);
                    }
                });
    }

    //生成预览图
    private void uploadModelThumbnail(String mFileId) {
        EasyHttp.post(EditModelPreviewActivity.this).api(new UpdateImageApi()
                        .setFileName(UUID.randomUUID() + ".jpg")
                        .setFile(thumbnailFile)
                        .setWatermark(true))
                .request(new HttpCallback<HttpData<UpdateImageApi.Bean>>(EditModelPreviewActivity.this) {
                    @Override
                    public void onSucceed(HttpData<UpdateImageApi.Bean> imageResult) {
                        Log.e("showProgressDialog==>", "预览图地址生成成功");
                        modelThumbnail = imageResult.getData().getUrl();
                        EasyHttp.post(EditModelPreviewActivity.this).api(new RelateThumbnailApi()
                                        .setThumbnail(modelThumbnail)
                                        .setFileId(mFileId))
                                .request(new HttpCallback<HttpData<UpdateImageApi.Bean>>(this) {
                                    @Override
                                    public void onSucceed(HttpData<UpdateImageApi.Bean> result) {
                                        Log.e("showProgressDialog==>", "预览图关联缩略图成功");
                                        dismissProgressDialog();
                                        ToastUtils.showShort("上传成功");
                                        Intent intent = new Intent();
                                        intent.putExtra(EditModelActivity.KEY_EDIT_MODEL_URL, modelUrl);
                                        intent.putExtra(EditModelActivity.KEY_EDIT_MODEL_THUMBNAIL, modelThumbnail);
                                        setResult(Activity.RESULT_OK, intent);
                                        finish();
                                    }
                                });
                    }
                });
    }

    //加载模型
    public void loadStlModel() {
        if (mFilePath.isEmpty()) {
            ToastUtils.showShort("模型地址为空");
            return;
        }
        STLViewBuilder.init(stlEditModelPreview).File(new File(mFilePath)).build();
        stlEditModelPreview.setScale(true);
        stlEditModelPreview.setRotate(true);
        stlEditModelPreview.setVisibility(View.VISIBLE);
        stlEditModelPreview.setOnReadCallBack(new OnReadCallBack() {
            @Override
            public void onStart() {

            }

            @Override
            public void onReading(int cur, int total) {

            }

            @Override
            public void onCreateBitmap(GL10 gl, int outputWidth, int outputHeight) {
                Bitmap bitmap = createBitmapFromGLSurface(0, 0, outputWidth, outputHeight, gl);//截取3D文件 生成Bitmap
                thumbnailFile = ThumbnailUtils.saveBitmapToFile(EditModelPreviewActivity.this, bitmap); // 将缩略图转成File
                Log.e("thumbnailFile", thumbnailFile.getPath());
            }

            @Override
            public void onFinish() {

            }
        });
    }

    private Bitmap createBitmapFromGLSurface(int x, int y, int w, int h, GL10 gl) {
        int bitmapBuffer[] = new int[w * h];
        int bitmapSource[] = new int[w * h];
        IntBuffer intBuffer = IntBuffer.wrap(bitmapBuffer);
        intBuffer.position(0);
        try {
            gl.glReadPixels(x, y, w, h, GL10.GL_RGBA, GL10.GL_UNSIGNED_BYTE,
                    intBuffer);
            int offset1, offset2;
            for (int i = 0; i < h; i++) {
                offset1 = i * w;
                offset2 = (h - i - 1) * w;
                for (int j = 0; j < w; j++) {
                    int texturePixel = bitmapBuffer[offset1 + j];
                    int blue = (texturePixel >> 16) & 0xff;
                    int red = (texturePixel << 16) & 0x00ff0000;
                    int pixel = (texturePixel & 0xff00ff00) | red | blue;
                    bitmapSource[offset2 + j] = pixel;
                }
            }
        } catch (GLException e) {
            return null;
        }
        return Bitmap.createBitmap(bitmapSource, w, h, Bitmap.Config.ARGB_8888);
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        stlEditModelPreview.setVisibility(View.VISIBLE);
        stlEditModelPreview.requestRedraw();
    }

    @Override
    protected void onStop() {
        super.onStop();
        stlEditModelPreview.setVisibility(View.GONE);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (oSSHelper != null) {
            oSSHelper.delete();
        }
    }
}
